package 重温_Java并发基础.ForkJoin框架案例;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * 使用forkjoin进行批量插入案例
 *
 * @author idea
 * @data 2019/11/10
 */
public class BatchInsertDemo extends RecursiveTask<Integer> {

    List<Integer> records;

    public BatchInsertDemo(List<Integer> records) {
        this.records = records;
    }

    @Override
    protected Integer compute() {
        if(records.size()<3){
            return computeDirectly();
        } else {
            int size=records.size();
            BatchInsertDemo aTask=new BatchInsertDemo(records.subList(0,size/2));

            BatchInsertDemo bTask=new BatchInsertDemo(records.subList(size/2,records.size()));
            //两个任务一起执行 forkjoin框架独有
            invokeAll(aTask,bTask);
            return aTask.join()+bTask.join();
        }
    }


    /**
     * 真正的插入数据之处
     *
     * @return
     */
    private int computeDirectly(){
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("插入了："+ Arrays.toString(records.toArray()));
        return records.size();
    }


    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ForkJoinPool forkJoinPool=new ForkJoinPool(100);
        List<Integer> list=new ArrayList<>();
        for(int i=0;i<100;i++){
            list.add(i);
        }

        BatchInsertDemo batchInsertTask = new BatchInsertDemo(list);
        long t1 = System.currentTimeMillis();
        ForkJoinTask<Integer> reslut = forkJoinPool.submit(batchInsertTask);
        System.out.println(reslut.get());
        long t2 = System.currentTimeMillis();
        System.out.println(t2-t1);
    }
}
